﻿using Janus.Cores.Tools;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;

namespace Janus.Mes.WebClient
{
    public static partial class MyHtmlHelper
    {
        static MyHtmlHelper()
        {

        }

        /// <summary>
        /// 格式化HTML
        /// </summary>
        /// <param name="sourcehtml"></param>
        /// <returns></returns>
        public static MvcHtmlString FormatHtml(object sourcehtml)
        {
            string html = string.Empty;
            if (sourcehtml != null)
            { html = sourcehtml.ToString(); }
            else
            {
                return new MvcHtmlString(null);
            }
            System.Text.RegularExpressions.Regex regex1 =
                     new System.Text.RegularExpressions.Regex(@"<script[sS]+</script *>",
                     System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex2 =
                  new System.Text.RegularExpressions.Regex(@" href *= *[sS]*script *:",
                  System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex3 =
                  new System.Text.RegularExpressions.Regex(@" no[sS]*=",
                  System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex4 =
                  new System.Text.RegularExpressions.Regex(@"<iframe[sS]+</iframe *>",
                  System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex5 =
                  new System.Text.RegularExpressions.Regex(@"<frameset[sS]+</frameset *>",
                  System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex6 =
                  new System.Text.RegularExpressions.Regex(@"<img[^>]+>",
                  System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex7 =
                  new System.Text.RegularExpressions.Regex(@"</p>",
                  System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex8 =
                  new System.Text.RegularExpressions.Regex(@"<p>",
                  System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex9 =
                  new System.Text.RegularExpressions.Regex(@"<[^>]*>",
                  System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            html = regex1.Replace(html, ""); //过滤<script></script>标记    
            html = regex2.Replace(html, ""); //过滤href=javascript: (<A>) 属性    
            html = regex3.Replace(html, " _disibledevent="); //过滤其它控件的on...事件    
            html = regex4.Replace(html, ""); //过滤iframe    
            html = regex5.Replace(html, ""); //过滤frameset    
            html = regex6.Replace(html, ""); //过滤frameset    
            html = regex7.Replace(html, ""); //过滤frameset    
            html = regex8.Replace(html, ""); //过滤frameset    
            html = regex9.Replace(html, "");
            //html = html.Replace(" ", "");   
            html = html.Replace("</strong>", "");
            html = html.Replace("<strong>", "");
            html = Regex.Replace(html, "[\f\n\r\t\v]", "");  //过滤回车换行制表符   
            return new MvcHtmlString(html);

        }

        public static string FormateUrl(this HtmlHelper htmlHelper, string currentUrl, string OpID, params string[] parmlist)
        {
            string url = null;
            if (currentUrl.IndexOf("OpID") < 0)
            {
                currentUrl = currentUrl + (currentUrl.IndexOf("?") >= 0 ? "&" : "?") + "OpID=" + OpID;
            }
            if (currentUrl.IndexOf("[") >= 0)
            {
                currentUrl = MyHtmlHelper.RegexUrl(htmlHelper, currentUrl);
            }
            currentUrl = currentUrl + "&" + string.Join("&", parmlist);
            var urlArry = currentUrl.Split('?');
            if (urlArry.Length > 2)
            {
                for (int i = 0; i < urlArry.Length; i++)
                {
                    url += urlArry[i];
                    if (i == 0)
                    { url += "?"; }
                    else
                    {
                        if (i < (urlArry.Length - 1))
                        {
                            url += "&";
                        }
                    }
                }
            }
            else
            {
                url = currentUrl;
            }
            while (url.IndexOf("&&") > 0)
            {
                url = url.Replace("&&", "&");
            }
            return url;
        }
        public static string RegexUrl(this HtmlHelper htmlHelper, string currentUrl)
        {
            string result = currentUrl;
            Regex regex = new Regex(@"\[\w+\]");
            var regResults = regex.Matches(currentUrl);
            for (int i = 0; i < regResults.Count; i++)
            {
                string rq = regResults[i].Value.Replace("[", "").Replace("]", "");
                string replaceElemt = string.Empty;
                if (rq.IndexOf("s_") == 0)
                {
                    replaceElemt = HttpContext.Current.Session[rq] as string;
                    //HttpContext.Current.Session[rq] = null;
                }
                else
                {
                    replaceElemt = HttpContext.Current.Request[rq];
                }
                result = result.Replace(regResults[i].Value, replaceElemt);
            }
            return result;
        }

        /// <summary>
        /// 拼装父级参数
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <returns></returns>
        public static string UrlQuerys(this HtmlHelper htmlHelper)
        {
            //获取父级的Router
            string querystring = "";
            var bRouteData = HttpContext.Current.Request.RequestContext.RouteData.Values;
            if (bRouteData != null)
            {
                bRouteData.Remove("area");
                bRouteData.Remove("controller");
                bRouteData.Remove("action");
                bRouteData.Remove("OpID");
            }

            if (bRouteData != null && bRouteData.Count() > 0)
            {
                foreach (KeyValuePair<string, object> item in bRouteData)
                {
                    querystring += string.Format("&{0}={1}", item.Key, item.Value);
                }
            }
            string currenturl = HttpContext.Current.Request.Url.ToString();
            string[] urls = null;
            if (!string.IsNullOrEmpty(currenturl))
            {
                urls = currenturl.Split('?');
            }
            if (urls.Length > 1)
            {
                var urlparams = urls[1].Split('&').ToList();
                var reusltParams = urlparams.Where(c => c.IndexOf("OpID") < 0
                                                    && c.Length > 0
                                                    && c.IndexOf("=") > 0
                                                    && c.IndexOf("LangType") < 0
                                                    && c.IndexOf("DIVGUID") < 0
                                                    && c.IndexOf("_=") < 0).ToList();
                querystring = querystring + "&" + string.Join("&", reusltParams);
            }
            return querystring;
        }

        public static void RenderActionUrl(this HtmlHelper htmlHelper, string url)
        {
            var bRouteData = HttpContext.Current.Request.RequestContext.RouteData.Values;
            if (bRouteData != null)
            {
                bRouteData.Remove("area");
                bRouteData.Remove("controller");
                bRouteData.Remove("action");
                bRouteData.Remove("OpID");
            }
            var arrayUrl = url.Split('?');
            var arrayRouter = arrayUrl[0].Split('/');
            if (arrayRouter.Length > 2)
            {
                string area = arrayRouter[0];
                string controllors = arrayRouter[1];
                string action = arrayRouter[2];
                string queryString = "";
                RouteValueDictionary routerVal = new RouteValueDictionary();
                routerVal.Add("area", area);
                if (arrayUrl.Length > 1)
                {
                    queryString = arrayUrl[1];
                    foreach (var item in queryString.Split('&'))
                    {
                        if (!string.IsNullOrEmpty(item))
                        {
                            string[] keyVals = item.Split('=');
                            if (keyVals.Length > 1)
                            {
                                if (!routerVal.ContainsKey(keyVals[0]))
                                {
                                    routerVal.Add(keyVals[0], Uri.EscapeDataString(keyVals[1]));
                                }
                            }
                        }
                    }
                }

                //获取父级的Router
                if (bRouteData != null && bRouteData.Count() > 0)
                {
                    foreach (KeyValuePair<string, object> item in bRouteData)
                    {
                        if (!routerVal.ContainsKey(item.Key))
                        {
                            routerVal.Add(item.Key, item.Value);
                        }
                    }
                }
                ChildActionExtensions.RenderAction(htmlHelper, action, controllors, routerVal);
            }
        }

        /// <summary>
        /// 小数格式化保留有效位
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="val"></param>
        /// <returns></returns>
        public static HtmlString DecimalFormat(this HtmlHelper htmlHelper, object val)
        {
            string result = DecimalFormats(htmlHelper, val);
            if (!string.IsNullOrEmpty(result))
            {
                result = "<div class=\"txtright\">" + result + "</div>";
            }
            return new HtmlString(result);
        }

        public static string DecimalFormats(this HtmlHelper htmlHelper, object val)
        {
            string result = null;
            if (val != null)
            {
                double v = 0;
                if (double.TryParse(val.ToString(), out v))
                {
                    result = v.ToString();
                }
            }
            return result;
        }
    }
}